package com.hq.fxh.No1_Infromation;

import android.Manifest;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.hq.fxh.HttpApi.UserServiceImpl;
import com.hq.fxh.Modle.CityUrlModle;
import com.hq.fxh.R;
import com.hq.fxh.Utils.LogUtils;
import com.hq.fxh.Utils.SharedPreferenceUtils;
import com.tencent.upload.common.Global;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

import cn.jiguang.net.HttpResponse;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Callback;

import static android.content.Context.LOCATION_SERVICE;
import static com.baidu.location.h.j.ad;
import static com.baidu.location.h.j.c;
import static com.baidu.location.h.j.e;
import static com.tencent.upload.common.Global.context;

/**
 * /**
 *
 * @author 薛
 * @ClassName
 * @Description :
 * @Created 2017/9/13
 * @Email xlwenhao1858@sina.com
 */


public class ShowLocation {

    private String provider;//位置提供器
    private LocationManager locationManager;//位置服务
    private Location location;
      String latitude;
    String longitude;

    Context context;


    public void getLocationMessage(Context context) {
        this.context = context;
        isOPen();
        initData();

    }


    public void initData() {
        locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);//获得位置服务
        provider = judgeProvider(locationManager);

        if (provider != null) {//有位置提供器的情况
            //为了压制getLastKnownLocation方法的警告
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                LogUtils.startToash(context, "请打开手机GPS");

                return;
            }
            location = locationManager.getLastKnownLocation(provider);
            if (location != null) {
                getLocation(location);//得到当前经纬度并开启线程去反向地理编码
            } else {
                LogUtils.startToash(context, "暂时无法获得当前位置");
             }
        } else {//不存在位置提供器的情况
            LogUtils.startToash(context, "手机不存在GPS");
        }
    }

    /**
     * 得到当前经纬度并开启线程去反向地理编码
     */
    public void getLocation(Location location) {
        latitude = location.getLatitude() + "";
        longitude = location.getLongitude() + "";
        LogUtils.e("经纬度" + latitude + "    " + longitude);
        String url = "http://api.map.baidu.com/geocoder/v2/?ak=pPGNKs75nVZPloDFuppTLFO3WXebPgXg&callback=renderReverse&location=" + latitude + "," + longitude + "&output=json&pois=0";
        new MyAsyncTask(url).execute();

      /* UserServiceImpl.getGpsCity(url, new Callback<CityUrlModle>() {
            @Override
            public void onResponse(retrofit2.Call<CityUrlModle> call, retrofit2.Response<CityUrlModle> response) {
                if (response.body() == null) {
                } else {
                    CityUrlModle.ResultBean.AddressComponentBean addressComponent = response.body().getResult().getAddressComponent();
                    if (addressComponent == null) {
                         return;
                    }
                    String city = addressComponent.getCity();
                    String adcode = addressComponent.getAdcode();
                    String district = addressComponent.getDistrict();
                    LogUtils.e("当前位置：" + city + district + "   小区编码" + adcode);

                }
            }

            @Override
            public void onFailure(retrofit2.Call<CityUrlModle> call, Throwable t) {
                LogUtils.e("当前位置：错误信息：" +t.getMessage());

            }
        });*/
    }

    /**
     * 判断是否有可用的内容提供器
     *
     * @return 不存在返回null
     */
    private String judgeProvider(LocationManager locationManager) {
        List<String> prodiverlist = locationManager.getProviders(true);
        if (prodiverlist.contains(LocationManager.NETWORK_PROVIDER)) {
            return LocationManager.NETWORK_PROVIDER;
        } else if (prodiverlist.contains(LocationManager.GPS_PROVIDER)) {
            return LocationManager.GPS_PROVIDER;
        } else {
            Toast.makeText(context, "没有可用的位置提供器", Toast.LENGTH_SHORT).show();
        }
        return null;
    }

    class MyAsyncTask extends AsyncTask<Void, Void, Void> {
        String url = null;//要请求的网址
        String str = null;//服务器返回的数据
        String address = null;

        public MyAsyncTask(String url) {
            this.url = url;
        }

        @Override
        protected Void doInBackground(Void... params) {
            OkHttpClient okHttpClient = new OkHttpClient();
            Request request = new Request.Builder().url(url).build();
            Call call = okHttpClient.newCall(request);
            try {
                Response response = call.execute();
                str = response.body().string();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            try {

                str = str.replace("renderReverse&&renderReverse", "");
                str = str.replace("(", "");
                str = str.replace(")", "");
                Gson gson = new Gson();
                try {
                    CityUrlModle cityUrlModle = gson.fromJson(str, CityUrlModle.class);
                    CityUrlModle.ResultBean citydata = cityUrlModle.getResult();
                    CityUrlModle.ResultBean.AddressComponentBean addressComponent = citydata.getAddressComponent();
                    String city = addressComponent.getCity();
                    String adcode = addressComponent.getAdcode();
                    String district = addressComponent.getDistrict();
                    int cityCode = citydata.getCityCode();
                    SharedPreferenceUtils.setCityCode(context, cityCode);
                    LogUtils.e("当前位置：" + city + district + "   小区编码" + adcode);
                } catch (Exception e) {
                    JSONObject jsonObject = new JSONObject(str);
                    JSONObject address = jsonObject.getJSONObject("result");
                    String city = address.getString("formatted_address");
                    String district = address.getString("sematic_description");

                    LogUtils.e("当前位置：" + city + district);

                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
            super.onPostExecute(aVoid);
        }
    }


    public final boolean isOPen() {
        LocationManager locationManager
                = (LocationManager) context.getSystemService(LOCATION_SERVICE);
        // 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快）
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        // 通过WLAN或移动网络(3G/2G)确定的位置（也称作AGPS，辅助GPS定位。主要用于在室内或遮盖物（建筑群或茂密的深林等）密集的地方定位）
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps  ) {
            return true;
        } else {
            openGPS(context);


        }

        return false;
    }


    public final void openGPS(Context context) {
        Intent GPSIntent = new Intent();
        GPSIntent.setClassName("com.android.settings",
                "com.android.settings.widget.SettingsAppWidgetProvider");
        GPSIntent.addCategory("android.intent.category.ALTERNATIVE");
        GPSIntent.setData(Uri.parse("custom:3"));
        try {
            PendingIntent.getBroadcast(context, 0, GPSIntent, 0).send();
            initData();

        } catch (PendingIntent.CanceledException e) {
            e.printStackTrace();
        }
    }

}